package com.ruoyi.flowable.listener.asset;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.Tables;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.deepoove.poi.policy.TableRenderPolicy;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.equ.domain.EquAsset;
import com.ruoyi.equ.domain.EquStockin;
import com.ruoyi.equ.service.IEquAssetService;
import com.ruoyi.equ.service.IEquStockinService;
import com.ruoyi.equ.util.PinyinUtils;
import com.ruoyi.flowable.domain.MockMultipartFile;
import com.ruoyi.flowable.domain.WorkOrderAssetRel;
import com.ruoyi.flowable.service.IWorkOrderAssetRelService;
import com.ruoyi.flowable.util.URLEncoderUtils;
import com.ruoyi.framework.config.ServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.ruoyi.flowable.listener.asset.AssetListener_2.getFileList;

/**
 * 验收-结束 资产设备id、资产编号、验收最终状态、验收完成时间
 */
@Slf4j
@Component("assetCompleteListener")
public class AssetCompleteListener implements ExecutionListener {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final IWorkOrderAssetRelService workOrderAssetRelService = SpringUtils.getBean(IWorkOrderAssetRelService.class);

    private static final ServerConfig serverConfig = SpringUtils.getBean(ServerConfig.class);
    private static final IEquStockinService stockinService = SpringUtils.getBean(IEquStockinService.class);
    private static final IEquAssetService assetService = SpringUtils.getBean(IEquAssetService.class);

    @Override
    @Transactional
    public void notify(DelegateExecution execution) {
        try {
            //asset入库、资产设备id
            Map<String, Object> map = setAsset(execution, assetService);
            //资产编号
            String assetNumber = (String) map.get("assetNumber");
            Long assetId = (Long) map.get("assetId");
            String assetName = (String) map.get("assetName");

            //验收最终状态
            String acceptanceStatus = "通过";

            //验收完成时间
            Date finishTime = sdfTime.parse(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            //备注
            String remark = assetName + "入库验收";

            EquStockin equStockin = execution.getVariable("equStockin", EquStockin.class);

            //审批信息
            String approvalInfo = equStockin.getApprovalInfo();
            Map<String, Object> approvalInfoMap = objectMapper.readValue(
                    approvalInfo,
                    new TypeReference<Map<String, Object>>() {
                    });
            approvalInfoMap.put("验收最终状态", acceptanceStatus);
            approvalInfoMap.put("验收完成时间", finishTime);
            approvalInfoMap.put("备注", remark);
            approvalInfo = objectMapper.writeValueAsString(approvalInfoMap);

            equStockin.setAssetId(assetId);
            equStockin.setAssetNumber(assetNumber);
            equStockin.setAcceptanceStatus(acceptanceStatus);
            equStockin.setFinishTime(finishTime);
            equStockin.setRemark(remark);

            equStockin.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            equStockin.setApprovalInfo(approvalInfo);

            //保存stokin
            stockinService.insertEquStockin(equStockin);

            //更新工单状态(流程实例和资产结合的工单)
            String processInstanceId = execution.getProcessInstanceId();
            WorkOrderAssetRel workOrderAssetRel = new WorkOrderAssetRel();
            workOrderAssetRel.setProcInsId(processInstanceId);
            workOrderAssetRel.setWorkOrderStatus("已完成");
            workOrderAssetRel.setFinishTime(new Date());
            //资产id、number
            workOrderAssetRel.setAssetId(assetId);
            workOrderAssetRel.setAssetNumber(assetNumber);
            //生成word
            String url = generateWord(execution.getVariables(), map);
            workOrderAssetRel.setFileUrl(url);
            workOrderAssetRelService.updateWorkOrderAssetRel(workOrderAssetRel);

        } catch (ParseException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    //生成word
    private String generateWord(Map<String, Object> variables, Map<String, Object> assetMap) throws IOException {
        BufferedInputStream resourceAsStream = new BufferedInputStream(
                Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("word/医院设备验收入库单.docx"))
        );
        // 使用配置编译模板
        XWPFTemplate template = XWPFTemplate.compile(resourceAsStream);
        Configure config = template.getConfig();

        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 修正日期格式
        String formattedDate = currentDate.format(formatter);

        HashMap<String, Object> finalMap = new HashMap<>();
        finalMap.put("入库单号", assetMap.get("assetNumber"));//assetNumber
        finalMap.put("入库日期", formattedDate);
        finalMap.put("设备名称", assetMap.get("assetName"));
        finalMap.put("设备型号规格", variables.get("modelSpec"));
        finalMap.put("生产厂家", variables.get("manufacturer"));
        finalMap.put("生产批号", variables.get("batchNumber"));
        finalMap.put("供应商名称", variables.get("supplier"));
        finalMap.put("采购合同编号", variables.get("contractNo"));
        finalMap.put("发票编号", variables.get("invoiceNumber"));
        finalMap.put("购置金额", variables.get("purchaseAmount"));
        if (variables.get("isTax").toString().equals("含税")) {
            finalMap.put("含税", "☑是 □ 否 ");
        } else if (variables.get("isTax").toString().equals("不含税")) {
            finalMap.put("含税", "□是 ☑ 否 ");
        }
        finalMap.put("预计使用年限", variables.get("serviceLife"));
        finalMap.put("质保开始日期", variables.get("warrantyStartTime"));
        finalMap.put("质保结束日期", variables.get("warrantyEndTime"));
        finalMap.put("接收科室", variables.get("acceptDept"));
        finalMap.put("存放地点", variables.get("storageLocation"));

        finalMap.put("实际到货日期", variables.get("arrivalDate"));
        finalMap.put("运输单位", variables.get("transportUnit"));
        finalMap.put("运输单号", variables.get("transportNo"));

        //packageStatus"完好"、"破损":□ 包装完好，无破损、挤压痕迹 □ 包装破损
        List<Map<String, String>> packageImages = (List<Map<String, String>>) variables.get("packageImage");
        finalMap.put("包装照片", Pictures.ofLocal(replaceUrl(packageImages.get(0).get("url"))).size(200, 80).create());
        config.customPolicy("包装照片", new PictureRenderPolicy());
        if (variables.get("packageStatus").toString().equals("完好")) {
            finalMap.put("包装状态1", "☑");
            finalMap.put("包装状态2", "□");
        } else if (variables.get("packageStatus").toString().equals("破损")) {
            finalMap.put("包装状态1", "□");
            finalMap.put("包装状态2", "☑");
            finalMap.put("异常描述", "（破损位置 / 程度：" + variables.get("exceptionDesc") + "）");
        }

        //sealStatus"完好"、"破损":□ 密封标识完好 □ 密封标识损坏
        if (variables.get("sealStatus").toString().equals("完好")) {
            finalMap.put("密封标识1", "☑");
            finalMap.put("密封标识2", "□");
        } else if (variables.get("sealStatus").toString().equals("损坏")) {
            finalMap.put("密封标识1", "□");
            finalMap.put("密封标识2", "☑");
            finalMap.put("异常描述", "（破损位置 / 程度：" + variables.get("exceptionDesc") + "）");
        }

        List<Map<String, String>> signature_act1 = (List<Map<String, String>>) variables.get("signature_act1");
        finalMap.put("开箱人签字", Pictures.ofLocal(replaceUrl(signature_act1.get(0).get("url"))).size(200, 80).create());
        config.customPolicy("开箱人签字", new PictureRenderPolicy());
        finalMap.put("开箱日期", variables.get("date2_2"));

        //表格
        RowRenderData rowRenderData = Rows.of("验收类别", "明细", "数量（应到 / 实到）", "规格型号核对结果", "备注").center().textBold().create();
        Tables.TableBuilder tableBuilder = Tables.of(rowRenderData);
        List<Map<String, Object>> equipmentForm = (List<Map<String, Object>>) variables.get("equipmentForm");
        for (int i = 0; i < equipmentForm.size(); i++) {
            if (i == 0) {
                tableBuilder.addRow(Rows.of("主机设备", equipmentForm.get(i).get("detail").toString(),
                        equipmentForm.get(i).get("yingnum") + "/" + equipmentForm.get(i).get("shinum"),
                        equipmentForm.get(i).get("xinghao").toString().equals("一致") ? "☑ 一致 □ 不一致" : "□ 一致 ☑ 不一致",
                        equipmentForm.get(i).get("remark").toString()).center().create());
            } else {
                tableBuilder.addRow(Rows.of("", equipmentForm.get(i).get("detail").toString(),
                        equipmentForm.get(i).get("yingnum") + "/" + equipmentForm.get(i).get("shinum"),
                        equipmentForm.get(i).get("xinghao").toString().equals("一致") ? "☑ 一致 □ 不一致" : "□ 一致 ☑ 不一致",
                        equipmentForm.get(i).get("remark").toString()).center().create());
            }
        }
        List<Map<String, Object>> attachmentForm = (List<Map<String, Object>>) variables.get("attachmentForm");
        for (int i = 0; i < attachmentForm.size(); i++) {
            if (i == 0) {
                tableBuilder.addRow(Rows.of("配套附件", attachmentForm.get(i).get("detail").toString(),
                        attachmentForm.get(i).get("yingnum") + "/" + attachmentForm.get(i).get("shinum"),
                        attachmentForm.get(i).get("xinghao").equals("一致") ? "☑ 一致 □ 不一致" : "□ 一致 ☑ 不一致",
                        attachmentForm.get(i).get("remark").toString()).center().create());
            } else {
                tableBuilder.addRow(Rows.of("", attachmentForm.get(i).get("detail").toString(),
                        attachmentForm.get(i).get("yingnum") + "/" + attachmentForm.get(i).get("shinum"),
                        attachmentForm.get(i).get("xinghao").equals("一致") ? "☑ 一致 □ 不一致" : "□ 一致 ☑ 不一致",
                        attachmentForm.get(i).get("remark").toString()).center().create());
            }
        }
        List<Map<String, Object>> toolForm = (List<Map<String, Object>>) variables.get("toolForm");
        for (int i = 0; i < toolForm.size(); i++) {
            if (i == 0) {
                tableBuilder.addRow(Rows.of("随机工具", toolForm.get(i).get("detail").toString(),
                        toolForm.get(i).get("yingnum") + "/" + toolForm.get(i).get("shinum"),
                        toolForm.get(i).get("xinghao").equals("一致") ? "☑ 一致 □ 不一致" : "□ 一致 ☑ 不一致",
                        toolForm.get(i).get("remark").toString()).center().create());
            } else {
                tableBuilder.addRow(Rows.of("", toolForm.get(i).get("detail").toString(),
                        toolForm.get(i).get("yingnum") + "/" + toolForm.get(i).get("shinum"),
                        toolForm.get(i).get("xinghao").equals("一致") ? "☑ 一致 □ 不一致" : "□ 一致 ☑ 不一致",
                        toolForm.get(i).get("remark").toString()).center().create());
            }
        }
        finalMap.put("表格", tableBuilder.create());
        config.customPolicy("表格", new TableRenderPolicy());

        String waiguan1 = variables.get("waiguan1").toString();
        String waiguan2 = variables.get("waiguan2").toString();
        String waiguan3 = variables.get("waiguan3").toString();
        if (waiguan1.equals("机身无划痕、变形、锈蚀")) finalMap.put("外观检查1", "☑");
        else finalMap.put("外观检查1", "□");
        if (waiguan2.equals("接口/按键完好")) finalMap.put("外观检查2", "☑");
        else finalMap.put("外观检查2", "□");
        if (waiguan3.equals("核心参数符合标准")) finalMap.put("外观检查3", "☑");
        else finalMap.put("外观检查3", "□");

        Object detail = variables.get("detail");
        if (ObjectUtils.isNotEmpty(detail)) {
            finalMap.put("存在问题", "☑ 存在问题：" + detail);
        }

        if (ObjectUtils.isNotEmpty(variables.get("fileupload4_2"))) {
            List<Map<String, Object>> fileupload4_2 = (List<Map<String, Object>>) variables.get("fileupload4_2");
            Map<String, Object> response = (Map<String, Object>) fileupload4_2.get(0).get("response");
            finalMap.put("测试图片", Pictures.ofLocal(replaceUrl(response.get("url").toString())).size(200, 80).create());
            config.customPolicy("测试图片", new PictureRenderPolicy());
        }

        String gongneng1 = variables.get("gongneng1").toString();
        String gongneng2 = variables.get("gongneng2").toString();
        String gongneng3 = variables.get("gongneng3").toString();
        if (gongneng1.equals("开机正常，无报错")) finalMap.put("功能测试1", "☑");
        else finalMap.put("功能测试1", "□");
        if (gongneng2.equals("核心功能运行达标")) finalMap.put("功能测试2", "☑");
        else finalMap.put("功能测试2", "□");
        if (gongneng3.equals("性能参数符合标准")) finalMap.put("功能测试3", "☑");
        else finalMap.put("功能测试3", "□");

        if (ObjectUtils.isNotEmpty(variables.get("canshu"))) {
            finalMap.put("参数值", "（参数值：" + variables.get("canshu").toString() + "）");
        }
        if (ObjectUtils.isNotEmpty(variables.get("miaoshu"))) {
            finalMap.put("测试异常", "☑ 测试异常：" + variables.get("miaoshu").toString());
        }

        String anquan1 = variables.get("anquan1").toString();
        String anquan2 = variables.get("anquan2").toString();
        String anquan3 = variables.get("anquan3").toString();
        if (anquan1.equals("接地正常")) finalMap.put("安全检查1", "☑");
        else finalMap.put("安全检查1", "□");
        if (anquan2.equals("绝缘性能达标")) finalMap.put("安全检查2", "☑");
        else finalMap.put("安全检查2", "□");
        if (anquan3.equals("符合医疗安全规范")) finalMap.put("安全检查3", "☑");
        else finalMap.put("安全检查3", "□");

        Object code = variables.get("code");
        if (ObjectUtils.isNotEmpty(code)) {
            finalMap.put("安全检测报告编号", "☑ 安全检测报告编号：" + code);
        }

        String flag4 = (String) variables.get("flag4");
        if (flag4.equals("0")) {
            finalMap.put("验收结论", "☑ 验收合格，同意入库 □ 验收不合格，需整改 □ 验收不合格，申请退换货");
        } else if (flag4.equals("1")) {
            Object yaoqiu = variables.get("yaoqiu");
            if (ObjectUtils.isNotEmpty(yaoqiu)) {
                finalMap.put("验收结论", "□ 验收合格，同意入库 ☑ 验收不合格，需整改（整改要求：" + yaoqiu + "） □ 验收不合格，申请退换货");
            }
            finalMap.put("验收结论", "□ 验收合格，同意入库 ☑ 验收不合格，需整改 □ 验收不合格，申请退换货");
        } else if (flag4.equals("2")) {
            finalMap.put("验收结论", "□ 验收合格，同意入库 □ 验收不合格，需整改 ☑ 验收不合格，申请退换货");
        }

        //4
        if (ObjectUtils.isNotEmpty(variables.get("signature_act4"))) {
            List<Map<String, String>> signature_act4 = (List<Map<String, String>>) variables.get("signature_act4");
            finalMap.put("技术验收人签字", Pictures.ofLocal(replaceUrl(signature_act4.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("技术验收人签字", new PictureRenderPolicy());
            finalMap.put("技术验收人签字日期", variables.get("date4_4"));
        }

        int index = 0;
        //5.1
        if (ObjectUtils.isNotEmpty(variables.get("signature_act5_1"))) {
            index++;
            finalMap.put("title" + index, index + ".\t采购部门意见：\n");
            finalMap.put("content" + index, "设备到货信息与采购合同一致，同意提交验收。\n负责人签字：");
            List<Map<String, String>> signature_act5_1 = (List<Map<String, String>>) variables.get("signature_act5_1");
            finalMap.put("签字" + index, Pictures.ofLocal(replaceUrl(signature_act5_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("签字" + index, new PictureRenderPolicy());
            finalMap.put("日期content" + index, "\n日期：");
            finalMap.put("日期" + index, variables.get("date5_1"));
        }
        //5.2
        if (ObjectUtils.isNotEmpty(variables.get("signature_act5_2"))) {
            index++;
            if (index != 1) {
                finalMap.put("title" + index, "\n" + index + ".\t资产管理部门意见：\n");
            }
            else {
                finalMap.put("title" + index, index + ".\t资产管理部门意见：\n");
            }
            finalMap.put("content" + index, "已核对设备信息，确认符合入库标准，同意登记资产。\n负责人签字：");
            List<Map<String, String>> signature_act5_2 = (List<Map<String, String>>) variables.get("signature_act5_2");
            finalMap.put("签字" + index, Pictures.ofLocal(replaceUrl(signature_act5_2.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("签字" + index, new PictureRenderPolicy());
            finalMap.put("日期content" + index, "\n日期：");
            finalMap.put("日期" + index, variables.get("date5_2"));
        }
        //5.3
        if (ObjectUtils.isNotEmpty(variables.get("signature_act5_3"))) {
            index++;
            if (index != 1) {
                finalMap.put("title" + index, "\n" + index + ".\t使用科室意见：\n");
            }
            else {
                finalMap.put("title" + index, index + ".\t使用科室意见：\n");
            }
            finalMap.put("content" + index, "☑ 同意接收，设备满足使用需求 □ 需进一步测试，暂不接收\n负责人签字：");
            List<Map<String, String>> signature_act5_3 = (List<Map<String, String>>) variables.get("signature_act5_3");
            finalMap.put("签字" + index, Pictures.ofLocal(replaceUrl(signature_act5_3.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("签字" + index, new PictureRenderPolicy());
            finalMap.put("日期content" + index, "\n日期：");
            finalMap.put("日期" + index, variables.get("date5_3"));
        }
        //5.4
        if (ObjectUtils.isNotEmpty(variables.get("signature_act5_4"))) {
            index++;
            if (index != 1) {
                finalMap.put("title" + index, "\n" + index + ".\t财务部门意见：\n");
            }
            else {
                finalMap.put("title" + index, index + ".\t财务部门意见：\n");
            }
            finalMap.put("content" + index, "已核对发票与设备信息，金额无误，同意后续付款流程。\n负责人签字：");
            List<Map<String, String>> signature_act5_4 = (List<Map<String, String>>) variables.get("signature_act5_4");
            finalMap.put("签字" + index, Pictures.ofLocal(replaceUrl(signature_act5_4.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("签字" + index, new PictureRenderPolicy());
            finalMap.put("日期content" + index, "\n日期：");
            finalMap.put("日期" + index, variables.get("date5_4"));
        }
        template.render(finalMap);

        // 生成临时文件
        String tempFileName = "设备验收单_" + assetMap.get("assetNumber") + "_" + System.currentTimeMillis() + ".docx";
        File tempFile = new File(System.getProperty("java.io.tmpdir"), tempFileName);

        try {
            template.writeToFile(tempFile.getAbsolutePath());
            log.info("Word文档生成成功，临时文件路径: {}", tempFile.getAbsolutePath());
            // 上传文件
            return uploadWordFile(tempFile, tempFileName);
            //本地路径
//            String wordPath = "D:\\项目学习\\若依工作流\\word\\aa.docx";
//            template.writeToFile(wordPath);
//            System.out.println("Word文档生成成功！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            template.close();
            resourceAsStream.close();
        }
    }

    // 上传Word文件
    public static String uploadWordFile(File file, String fileName) {
        try {
            // 读取文件内容到MultipartFile
            MultipartFile multipartFile = new MockMultipartFile(
                    fileName,
                    fileName,
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    Files.newInputStream(file.toPath())
            );
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String newFileName = FileUploadUtils.upload(filePath, multipartFile);
            // 获取服务器配置
            String url = serverConfig.getUrl() + newFileName;
            //截取/profile
            String result = url.substring(url.indexOf("/profile"));
            log.info("Word文档上传成功，访问URL: {}", result);
            return result;
        } catch (Exception e) {
            log.error("Word文档上传失败", e);
            throw new RuntimeException("Word文档上传失败", e);
        } finally {
            // 确保无论上传成功还是失败，都删除临时文件
            if (file != null && file.exists()) {
                try {
                    boolean deleted = file.delete();
                    if (deleted) {
                        log.info("临时文件已删除: {}", file.getAbsolutePath());
                    } else {
                        log.warn("临时文件删除失败: {}", file.getAbsolutePath());
                        // 如果第一次删除失败，尝试在JVM退出时删除
                        file.deleteOnExit();
                    }
                } catch (Exception e) {
                    log.warn("删除临时文件时发生异常: {}", file.getAbsolutePath(), e);
                    file.deleteOnExit();
                }
            }
        }
    }

    //asset入库
    private Map<String, Object> setAsset(DelegateExecution execution, IEquAssetService assetService) throws ParseException {
        //资产设备id、新增设备、获取id
        String assetName = execution.getVariable("assetName", String.class);
        String acceptDept = execution.getVariable("acceptDept", String.class);
        String assetBrand = execution.getVariable("assetBrand", String.class);
        //规则：YYSB-年份-科室缩写-序号，如YYSB-2025-NK-001
        String assetNumber = generateAssetNumber(acceptDept);
        String assetType = execution.getVariable("assetType", String.class);
        //设备配置('普通设备','大型设备','环保设备')
//            String assetSetup = execution.getVariable("assetSetup", String.class);
        String modelSpec = execution.getVariable("modelSpec", String.class);
        String batchNumber = execution.getVariable("batchNumber", String.class);
        String manufacturer = execution.getVariable("manufacturer", String.class);
        String packageImage = getFileList(execution, "packageImage").get(0);
        String supplier = execution.getVariable("supplier", String.class);
        String checkReport = getFileList(execution, "checkReport").get(0);
        String certificate = getFileList(execution, "certificate").get(0);
        String contractNo = execution.getVariable("contractNo", String.class);
        String invoiceNumber = execution.getVariable("invoiceNumber", String.class);
        String isTax = execution.getVariable("isTax", String.class);
        Date arrivalDate = sdf.parse(execution.getVariable("arrivalDate", String.class));
        String transportUnit = execution.getVariable("transportUnit", String.class);
        String transportNo = execution.getVariable("transportNo", String.class);
        BigDecimal purchaseAmount = new BigDecimal(execution.getVariable("purchaseAmount", String.class));
        Long serviceLife = Long.valueOf(execution.getVariable("serviceLife", String.class));
        Date warrantyStartTime = sdf.parse(execution.getVariable("warrantyStartTime", String.class));
        Date warrantyEndTime = sdf.parse(execution.getVariable("warrantyEndTime", String.class));
        //当前使用科室（如“内科”“儿科”）
        String useDept = execution.getVariable("acceptDept", String.class);
        String storageLocation = execution.getVariable("storageLocation", String.class);
        String numStr = execution.getVariable("num", String.class);
        Long num = null;
        if (numStr != null && !numStr.equals("")) {
            num = Long.valueOf(numStr);
        }
        //购置日期
//        String purchaseDate = execution.getVariable("purchaseDate", String.class);
        //累计折旧金额（元）
//        String accumulatedDepreciation = execution.getVariable("accumulatedDepreciation", String.class);
        //资产账面净值（元，购置金额-累计折旧）
//        String bookValue = execution.getVariable("bookValue", String.class);
        //资产状态
//        String assetStatus = execution.getVariable("assetStatus", String.class);
        //其他信息
//        String otherInfo = execution.getVariable("otherInfo", String.class);
        Long userId = SecurityUtils.getUserId();

        EquAsset equAsset = new EquAsset();
        equAsset.setAssetName(assetName);
        equAsset.setAssetNumber(assetNumber);
        equAsset.setAssetBrand(assetBrand);
        equAsset.setAssetType(assetType);
        equAsset.setModelSpec(modelSpec);
        equAsset.setBatchNumber(batchNumber);
        equAsset.setManufacturer(manufacturer);
        equAsset.setPackageImage(packageImage);
        equAsset.setSupplier(supplier);
        equAsset.setCheckReport(checkReport);
        equAsset.setCertificate(certificate);
        equAsset.setContractNo(contractNo);
        equAsset.setInvoiceNumber(invoiceNumber);
        equAsset.setIsTax(isTax);
        equAsset.setArrivalDate(arrivalDate);
        equAsset.setTransportUnit(transportUnit);
        equAsset.setTransportNo(transportNo);
        equAsset.setPurchaseAmount(purchaseAmount);
        equAsset.setServiceLife(serviceLife);
        equAsset.setWarrantyStartTime(warrantyStartTime);
        equAsset.setWarrantyEndTime(warrantyEndTime);
        equAsset.setAcceptDept(acceptDept);
        equAsset.setUseDept(useDept);
        equAsset.setStorageLocation(storageLocation);
        equAsset.setNum(num);
        equAsset.setUserId(userId);
        equAsset.setRemark(assetName + "入库验收");

        equAsset.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());

        assetService.insertEquAsset(equAsset);
        Map<String, Object> map = new HashMap<>();
        map.put("assetNumber", assetNumber);
        map.put("assetId", equAsset.getAssetId());
        map.put("assetName", equAsset.getAssetName());
        return map;
    }

    /**
     * 获取唯一序列
     *
     * @param acceptDept
     * @return
     */
    private String generateAssetNumber(String acceptDept) {
        // 1. 获取当前年份
        String year = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy"));
        // 2. 获取科室缩写
        String deptAbbr = PinyinUtils.getDeptAbbreviation(acceptDept);
        // 3. 生成序号（基于时间戳的短序号）
        String sequence = generateTimestampSequence();
        // 4. 组合成完整的资产编号
        return String.format("YYSB-%s-%s-%s", year, deptAbbr, sequence);
    }

    /**
     * 使用时间戳生成更短的序号（如果不想依赖数据库查询）
     */
    private String generateTimestampSequence() {
        // 获取当前时间戳的后6位，确保长度适中
        long timeStamp = System.currentTimeMillis();
        String timeStampStr = String.valueOf(timeStamp);
        String shortTimestamp = timeStampStr.substring(timeStampStr.length() - 6);
        // 转换为数字并取模，得到4位数字
        int sequence = Integer.parseInt(shortTimestamp) % 10000;
        return String.format("%04d", sequence);
    }

    /**
     * 替换为本地路径
     */
    public static String replaceUrl(String url) {
        try {
            String replacedUrl = url.replace("/dev-api/profile", RuoYiConfig.getProfile())
                    .replace("/profile", RuoYiConfig.getProfile());
            return replacedUrl;
        } catch (Exception e) {
            System.err.println("URL处理失败: " + e.getMessage());
            return url;
        }
    }

    public static String replaceLocalhostWithIP(String url) {
        return null;
    }
}
